# -*- coding:utf-8 -*-
'''
     I should generate measurementdata using my ground truth propagator.
     
'''
import glob,os
import numpy as np
from aod.satellite import *
from aod.satProp import *
from aod.utils import *
import dataread
import copy
from  dataAnalyse import transmitSatMeanDataToReadble,dumpSatREcordtoMatlab
import simSettings as settings


np.random.seed(123)
measurementFolder = settings.SIMU_MEASUREMENT_FOLDER

## delete temporary data
for f in glob.glob(measurementFolder+ "*.npy"):
    os.remove(f)

# each linkInterval, each two sats will establish link
# we don't consider the visibility(Line of Sight)
linkInterval = 100

# timedrift: distance equvilent, it is equal to t_rec - t_trans
timedrift = 0 

loadProgressFile = './data/progressData/defaultprogress-gen.data'
progressData =  dataread.readProgressData(loadProgressFile)

satTrueStateFolder = settings.SIMU_TRUE_STATE_FOLDER
sats = []
satnum  =24 
roundTimeInterval = 4

simTime = settings.SIM_LENGTH
for i in range(0,satnum):
    satInitState     = progressData['satInitState'][i]
    satTimeDrift     = progressData['satTimeDrift'][i]
    satInitKineSate  = cStateWrapper(np.array(satInitState['mean']).reshape((6,)),satInitState['cov'])
    timeDrift        = cStateWrapper(np.array(satTimeDrift['mean']).reshape((1,)),np.array(satTimeDrift['cov'],dtype=float))

    sat              = cSat('sat'+str(i+1),satInitKineSate,timeDrift)
    sat.setCurTime(progressData['satCurrentTime'][i])
    sat.recordFileLength = 10000
    sat.initialRecord(satTrueStateFolder+sat.name)
    sat.setRecordProgress()
    sat.dataIndex = sat.dataIndex-1
    sat.useTruePropagator()
    sats.append(sat) # satnum is index +1
loadProgressFile1 = './data/progressData/defaultprogress-gen.data'
dataread.dumpProgressData(loadProgressFile1,sats)

initialTimeFile = measurementFolder + "initTime.txt"
f = open(initialTimeFile,'w')
f.write("%0.12f"%progressData['satCurrentTime'][0])
f.close()

initialfile  = measurementFolder+'Init_Orbit.txt'
f = open(initialfile,'w')
for i in range(1,satnum+1):
    metadata = [i]
    metadata.extend(sats[i-1].kine.mean.tolist())
    f.write(' '.join(str(x) for x in metadata)+'\n')
f.close()

fhandles = []
for i in range(1,satnum+1):
    filename   =measurementFolder+"H82-Sat%02d"%i+'-01.txt'
    fhandles.append(open(filename,'w'))

frontTime = progressData['satCurrentTime'][0]
for simcount in range(0,simTime):
    print "simcount:",simcount
    links =  genLinkPair(satnum)
    for link in links:
        data = []
        emitSat = sats[link[0]-1]
        recSat  = sats[link[1]-1]
        link1endTime  = frontTime
        emitSat.prop(endTime = frontTime)
        recSat.prop(endTime = frontTime)
        # record
        emitSat.recordNow()
        recSat.recordNow()
        # tempEmitSat  = copy.deepcopy(emitSat)
        # tempRecSat   = copy.deepcopy(recSat)
        tempEmitSat  = emitSat
        tempRecSat   = recSat
        measurement1, link1startTime = linkdata(tempEmitSat,tempRecSat,link1endTime,False)
        # print measurement,link1startTime
        link2endTime = frontTime+roundTimeInterval
        emitSat.prop(endTime = link2endTime)
        recSat.prop(endTime = link2endTime)
        emitSat.recordNow()
        recSat.recordNow()
        # tempEmitSat  = copy.deepcopy(emitSat)
        # tempRecSat   = copy.deepcopy(recSat)
        tempEmitSat  = emitSat
        tempRecSat   = recSat
        measurement2, link2startTime = linkdata(tempRecSat,tempEmitSat,link2endTime,False)
        data.append([0,int((link1endTime)/604800),(link1endTime)%604800,link[0],link[1],measurement1,0])
        data.append([0,int((link2endTime)/604800),(link2endTime)%604800,link[1],link[0],measurement2,0])
        
        str1 = ''
        for metadata in data:
            str1 = str1 + ' '.join(str(x) for x in metadata)+'\n'
        fhandles[link[0]-1].write(str1)
        fhandles[link[1]-1].write(str1)

    frontTime = frontTime + linkInterval

for i in range(0,satnum):
    sats[i].dumpRecords()
    fhandles[i].close()

# to be readable 
satIndices = list(range(1,25))
transmitSatMeanDataToReadble(satTrueStateFolder,satIndices)

dumpSatREcordtoMatlab(satTrueStateFolder,satIndices)